package com.boarsoft.boar.config.client.plugin;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.boarsoft.boar.config.client.listener.ConfigVarChangeListener;
import com.boarsoft.config.client.PropVarSyncImpl;
import com.boarsoft.config.core.*;
import com.boarsoft.config.manager.PropConfigManager;
import com.boarsoft.config.plugin.ConfigPlugin;
import com.boarsoft.config.spring.util.SpringContextUtil;
import com.boarsoft.config.util.ConfigUtils;

/**
 * 基于boar-client封装的扩展插件
 *
 */
public class BoarConfigPlugin implements ConfigPlugin {

	private ConfigFileSyncImpl configFileSync;
	private PropVarSyncImpl propVarSync;

	@Override
	public void init() {
		this.configFileSync = SpringContextUtil.getBean(ConfigFileSyncImpl.class);
		this.propVarSync = SpringContextUtil.getBean(PropVarSyncImpl.class);
		initPropConfig();
		initFileConfig();
	}

	public void initPropConfig() {
		ConcurrentHashMap<String, Object> configMap = PropConfigManager.getAllResource();
		for (String resourceId : configMap.keySet()) {
			String group = resourceId.substring(resourceId.lastIndexOf(".") + 1);
			List<Config> configs = ConfigHttpPuller.getConfig(group);
			Map<String, Object> param = new HashMap<>();
			propVarSync.getConfigListenerMap().put(group, new ConfigListenerImpl());
			for (Config config : configs) {
				param.put(config.getName(), config.getValue());
			}
			try {
				ConfigUtils.setProperties(configMap.get(resourceId), param);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	public void initFileConfig() {
		for (String namespace : configFileSync.getFileConfigMap().keySet()) {
			String fp = configFileSync.getFileConfigMap().get(namespace);
			try {
				String content = ConfigHttpPuller.getConfigFile(namespace);
				if (content == null) {
					continue;
				}
				configFileSync.save(fp, content.getBytes(StandardCharsets.UTF_8));
				ConfigListener configListener = configFileSync.getConfigListener(namespace);
				if (configListener != null) {
					configListener.onReady(fp);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public void refresh() {

	}
}
